package com.ugoodtech.mdcc.web.controller;

/* Copyright (C) Ugoodtech, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by Stone Shaw, 15/11/19
 */


import com.ugoodtech.mdcc.core.domain.Photo;
import com.ugoodtech.mdcc.core.service.PhotoService;
import com.ugoodtech.mdcc.web.dto.JsonException;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.PhotoResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@ApiIgnore
@Controller
@RequestMapping("/files")
public class FileController extends BaseController {

    @Autowired
    PhotoService photoService;




    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse uploadPhoto(
            @RequestParam(value = "categoryId") Long categoryId,
            @RequestParam(value = "file") MultipartFile file,
            @RequestParam(value = "osType", required = false) String osType,
            @RequestParam(value = "osVersion", required = false) String osVersion
    ) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------uploadPhoto---------------");
            logger.debug("categoryId  = " + categoryId);
            logger.debug("osType  = " + osType);
            logger.debug("osVersion : " + osVersion);

            logger.debug("imageSize  = " + file.getSize());
            logger.debug("imageOriginalFilename  = " + file.getOriginalFilename());
            logger.debug("imageContentType : " + file.getContentType());
        }

        Photo photo = photoService.savePhotoFile(file.getBytes(), file.getOriginalFilename(), categoryId);

        if (null != photo) {
            logger.debug("photoId : " + photo.getId());
            return JsonResponse.successResponseWithData(PhotoResponse.turnPhotoToResponse(photo));
        } else {
            logger.debug("上传照片失败，数据异常");
            logger.debug("--------------------------------------");
            return JsonResponse.errorResponseWithError("上传照片失败，数据异常", "上传照片失败，数据异常");
        }

    }


    @RequestMapping("/getFile")
//    @ResponseBody
    public void getPhoto(HttpServletResponse response,
                         @RequestParam(value = "fileId") String fileId
    ) throws Exception {


        if (logger.isDebugEnabled()) {
            logger.debug("--------------getPhoto---------------");
            logger.debug("photoId  = " + fileId);
        }

        if (null == this.getCurrentUser()) {
            throw new JsonException("notLogin");
        }
        byte[] bytes;
        Photo photo = photoService.getPhotoById(Long.parseLong(fileId));
        try {

            bytes = photoService.getPhotoBytes(Long.parseLong(fileId));

        } catch (IOException e) {
            e.printStackTrace();
            logger.debug("获取图片异常");
            throw new Exception("获取图片异常");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            logger.debug("获取图片参数异常");
            throw new Exception("获取图片参数异常");
        }
//        String extensionName = "jpg";
//        response.setContentType("image/" + extensionName);
        String codedFileName = java.net.URLEncoder.encode(photo.getName(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment;   filename=" + codedFileName);
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
    }


    @ResponseBody
    @RequestMapping(value = "/getFiles", method = RequestMethod.GET)
    public JsonResponse getFiles(

            String searchParam,
            Pageable pageable) {
        if (null == this.getCurrentUser()) {
            throw new JsonException("notLogin");
        }
        Page<Photo> files = photoService.queryFiles(null, null, null, pageable, searchParam, null);
        if (null != files.getContent() && files.getContent().size() > 0) {
            for (Photo photo : files.getContent()) {

            }
        }
        return JsonResponse.successResponseWithPageData(files);
    }

    @ResponseBody
    @RequestMapping(value = "/hiddenFile", method = RequestMethod.POST)
    public JsonResponse hiddenFile(
            Long fileId) {
        if (null == this.getCurrentUser()) {
            throw new JsonException("notLogin");
        }
        Photo file = photoService.getPhotoById(fileId);
        file.setEnabled(!file.getEnabled());
        photoService.save(file);
        return JsonResponse.successResponse();
    }

    Logger logger = LoggerFactory.getLogger(FileController.class);
}
